import React, { Component, PropTypes } from 'react'
import { deepFullCopy, messages, queryCurrencyPrecision } from "share/common";
import { Col, message, Modal, Popover, Row, Spin } from "antd";
import ResizeTable from "components/resize-table";
import moment from 'moment'
import borrowService from "../borrow-and-return.service";

class TransactionModal extends Component {

  onSelectChange = selectedRowKeys => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    if (selected) {
      this.setState({editTransaction: record});
    }
  };

  transactionColumns = [
    {
      title: messages('finance-1.key219')/*交易日期*/, dataIndex: 'createdDate',
      render: value =>  moment(value).format('YYYY-MM-DD')
    },
    {
      title: messages('finance-1.key220')/*付款流水号*/, dataIndex: 'transactionDetailCode',
      render: value => <Popover placement={'topLeft'} content={value}>{value}</Popover>
    },
    {
      title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode'
    },
    {
      title: messages('common.total.amount')/*总金额*/, dataIndex: 'amount',
      render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))
    },
    {
      title: messages('finance-1.key221')/*可还款金额*/, dataIndex: 'repaymentValue',
      render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))
    }
  ];

  state = {
    transactionList: [],
    rowSelection: {
      type: 'radio',
      selectedRowKeys: [],
      onChange: this.onSelectChange,
      onSelect: this.onSelectItem
    },
    editTransaction: {},
    info: {},
    modalShow: false,
    loading: false
  };

  componentWillReceiveProps = nextProps => {
    if (nextProps.record.id && nextProps.record.id !== this.props.record.id) {
      this.getList(nextProps.record, nextProps.onOK)
    }
  };

  getList = (record, onOk) => {
    this.setState({ loading: true });
    borrowService.getTransactionList(record.id).then(res => {
      if(res.data.length === 0){
        message.error(messages('finance-1.key222')/*该借款行无支付流水*/);
        this.setState({ loading: false });
        return -1;
      }
      let temp = {
        transactionList: res.data,
        loading: false
      };
      let infoRecord = deepFullCopy(record);
      if (res.data.length > 1) {
        this.setState({
          transactionList: res.data,
          loading: false,
          info: infoRecord,
          modalShow: true
        });
      } else {
        infoRecord.stayWriteoffAmount = res.data[0].repaymentValue;
        infoRecord.transactionDetailId = res.data[0].transactionDetailId;
        infoRecord.transactionDetailCode = res.data[0].transactionDetailCode;
        infoRecord.companyOID = res.data[0].paymentCompanyOID;
        infoRecord.legalEntityId = res.data[0].legalEntityId;
        infoRecord.companyId = res.data[0].paymentCompanyId;
        infoRecord.companyName = res.data[0].paymentCompanyName;
        this.setState({ loading: false }, onOk(infoRecord));
      }
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  turnToRepayment = () => {
    const { editTransaction, info } = this.state, { onOK } = this.props;
    if(Object.keys(editTransaction).length === 0){
      message.error(messages('finance-1.key223')/*请选择支付流水号*/);
      return -1;
    }
    info.stayWriteoffAmount = editTransaction.repaymentValue;
    info.transactionDetailId = editTransaction.transactionDetailId;
    info.transactionDetailCode = editTransaction.transactionDetailCode;
    info.companyOID = editTransaction.paymentCompanyOID;
    info.legalEntityId = editTransaction.legalEntityId;
    info.companyId = editTransaction.paymentCompanyId;
    info.companyName = editTransaction.paymentCompanyName;
    this.setState({ modalShow: false, info }, () => {
      onOK(info);
    })
  };

  render() {
    const { transactionList, modalShow, loading, rowSelection } = this.state;
    return (
      <div>
        {
          loading ? <Spin/> : <Modal
            visible={modalShow}
            width={700}
            title={messages('finance-1.key224')/*选择支付流水*/}
            onOk={this.turnToRepayment}
            onCancel={() => {
              rowSelection.selectedRowKeys = [];
              this.setState({
                modalShow: false,
                rowSelection,
                editTransaction: {}
              })
            }}
          >
            <Row>
              <Col span={11}> {messages('finance-1.key74')/*借款单号*/}：{transactionList[0] ? transactionList[0].businessCode : '-'}
              </Col>
              <Col span={12} offset={1}> {messages('finance-1.key6')/*借款行号*/}：{transactionList[0] ? transactionList[0].sequence : '-'}
              </Col>
            </Row>
            <Row>
              <Col span={11}> {messages('finance-1.key70')/*收款人*/}：{transactionList[0] ? transactionList[0].payeeName : '-'}
              </Col>
              <Col span={12} offset={1}> {messages('finance-1.key17')/*借款类型*/}：{transactionList[0] ? transactionList[0].loanTypeName : '-'}
              </Col>
            </Row>
            <ResizeTable
              dataSource={transactionList}
              rowSelection={rowSelection}
              rowKey="transactionDetailId"
              columns={this.transactionColumns}
              bordered
            />
          </Modal>
        }
      </div>
    )
  }

  static propTypes = {
    record: PropTypes.object,
    onOK: PropTypes.func
  }

}

export default TransactionModal;
